<template>
    <uni-drawer
        ref="uDrawerRefDom"
        :width="drawerWidthStyle"
        mode="left"
        :mask-click="true"
        @change="onWatchDrawer"
        @mask="onTapDrawerMask"
    >
        <!-- 抽屉内容容器 -->
        <view :class="[ns.b(), systemStore.safeAreaBottomClass]" :style="headerStyle">
            <view class="drawer-content">
                <view class="">
                    <text>晚上好</text>
                </view>
            </view>
        </view>
    </uni-drawer>
</template>

<script setup lang="ts">
import type { Ref } from "vue";
import { useSystemStore } from "@/store";
import UniDrawer from "@/custom-ui/uni-ui/lib/uni-drawer/uni-drawer.vue";
import { useNamespace } from "@/hooks";

const ns = useNamespace("menu-group");
const systemStore = useSystemStore();

/**
 * 计算抽屉头部样式，基于系统安全区域状态栏样式
 * @returns {Object} 返回包含安全区域状态栏样式的对象
 */
const headerStyle = computed(() => {
    return {
        ...systemStore.safeAreaStatusBarStyle
    };
});

const modelValue = defineModel({
    type: Boolean,
    default: false
});

const emits = defineEmits(["change"]);

const props = defineProps({
    width: {
        type: Number,
        default: 0
    }
});

const uDrawerRefDom: Ref<InstanceType<typeof UniDrawer> | null> = ref(null);

/**
 * 计算抽屉宽度样式
 * @returns {number} 返回传入的宽度值
 */
const drawerWidthStyle = computed(() => {
    return props.width as number;
});

/**
 * 控制抽屉的打开或关闭状态
 * @param {boolean} status - 抽屉的目标状态，true 表示打开，false 表示关闭
 */
const onUpdateDrawer = (status: boolean) => {
    if (!uDrawerRefDom.value) return;
    const method = status ? "open" : "close";
    uDrawerRefDom.value![method]();
};

/**
 * 监听抽屉状态变化事件
 * @param {boolean} status - 抽屉当前的状态
 */
const onWatchDrawer = (status: boolean) => {
    modelValue.value = status;
    emits("change", status);
};

/**
 * 处理点击抽屉遮罩事件
 * @param {boolean} status - 抽屉当前的状态
 */
const onTapDrawerMask = (status: boolean) => {
    modelValue.value = status;
    emits("change", status);
};

// 监听 modelValue 属性变化以同步抽屉状态
watch(
    () => modelValue.value,
    (status) => {
        onUpdateDrawer(status);
    }
);

// 组件挂载后初始化抽屉状态
onMounted(() => {
    onUpdateDrawer(modelValue.value as boolean);
});

// 暴露组件属性供外部访问
defineExpose({
    width: drawerWidthStyle
});
</script>

<style scoped lang="scss">
@import "./index";
</style>
